<template>
  <div class="list">
    <!-- 搜索 v-show="state.searchState.show"-->
    <Row class="search-filter" :class="{'active':searchState}">
      <Col>
        <Card style="height: 125px;">
          <Form :label-width="80" inline>
            <Form-item label="模板">
              <Input v-model="formItem.name" placeholder="请输入模版名称" style="width:187px"></Input>
            </Form-item>
            <Form-item>
              <div class="clearfix">
                <span class="pull-right">
                  <Button type="primary" icon="ios-search" shape="circle" @click="queryTableList()">查询</Button>
                </span>
              </div>
            </Form-item>
          </Form>
        </Card>
      </Col>
    </Row>
    <!-- 搜索 /-->
    <Row>
      <Col>
        <Card>
          <div slot="title">
            <Icon type="ios-film-outline"></Icon>固定表头
            <Button type="dashed" @click.native="fixedHeader=!fixedHeader">
              <Icon type="pin"></Icon>
            </Button>
            <Button type="success" @click="addOpen()">
              <Icon type="plus"></Icon>新增
            </Button>
            <Button type="primary" @click="searchShow" shape="circle">
              <Icon type="funnel"></Icon>筛选
            </Button>
          </div>

          <a href="#" slot="extra" @click.prevent="refresh">
            <Icon type="ios-loop-strong"></Icon>
          </a>
          <Table :loading="TableLoading" :show-header="showHeader" :height="fixedHeader ? 350 : ''" :data="listData" :columns="columns1" ref="table" @on-select="onSelect"
            @on-selection-change="onSelectionChange"></Table>
          <Row type="flex" justify="center">
            <Col>
              <Page :id="pageId" :total="totalSize" show-total show-sizer show-elevator @on-change="changeCurrent" @on-page-size-change="changePageSize" :current.sync="current" style="margin: 24px 0 24px;text-align:right"></Page>
            </Col>
            <Col push="1">
              <Button style="margin-top: 4vh;" type="primary" @click="goElevatorPage(pageId)">跳转</Button>
            </Col>
          </Row>
        </Card>
      </Col>
    </Row>

    <!-- 短信测试 -->
    <Modal v-model="testModal" v-if="DateReady" title="短信模板测试" width="650" :mask-closable="false">
      <Form :label-width="120">
        <Form-item label="短信测试" required>
          <Input v-model="test_info.phone" type="textarea" width="450" :autosize="{minRows: 3,maxRows: 8}" placeholder="请输入手机号码并以半角;分隔"></Input>
        </Form-item>
      </Form>
      <div slot="footer">
        <i-button type="primary" size="large" long :loading="loading" @click="testInfo()" icon="checkmark-round">保存</i-button>
      </div>
    </Modal>

    <Modal v-model="addModal" v-if="DateReady" title="新增短信" width="650" :mask-closable="false">
      <Alert>
        <p>模板变量编辑说明：</p>
        <p>输入#姓名#会调用短信接收者姓名字段</p>
        <p>输入#消费门店#会调用此会员最近一次消费门店或线上平台简称字段</p>
      </Alert>
      <Form :model="add_info" :label-width="80" ref="add_info" :rules="add_ruleValidate">
        <FormItem label="模板名称" prop="name">
          <Input v-model="add_info.name" placeholder="例如：周年庆送积分"></Input>
        </FormItem>

        <FormItem label="模板内容" required prop="contents">
          <Input v-model="add_info.contents" type="textarea" id="myinput" width="450" :autosize="{minRows: 3,maxRows: 8}" placeholder="#姓名#,本月是您入会周年庆,3倍积分等你来哦"></Input>
        </FormItem>
        <FormItem label="通道" prop="communicationVendorId">
          <Select v-model="add_info.communicationVendorId" placeholder="请选择" clearable>
            <Option v-for="item in cVendorsList" :value="item.id" :key="item.vendorName">{{ item.vendorName }}</Option>
          </Select>
        </FormItem>
      </Form>

      <Alert type="warning">字符数：{{add_info.length}}</Alert>
      <div slot="footer">
        <Button size="large" type="primary" long @click="addInfo('add_info')" :loading="loading">保存</Button>
      </div>
    </Modal>
    <Modal v-model="editModal" :closable=false title="编辑短信" width="650">
      <Alert>
        <p>模板变量编辑说明：</p>
        <p>输入#姓名#会调用短信接收者姓名字段</p>
        <p>输入#消费门店#会调用此会员最近一次消费门店或线上平台简称字段</p>
      </Alert>
      <Form :model="add_info" :label-width="80" ref="add_info" :rules="add_ruleValidate">
        <FormItem label="模板名称" prop="name">
          <Input v-model="add_info.name" placeholder="例如：周年庆送积分"></Input>
        </FormItem>

        <FormItem label="模板内容" required prop="contents">
          <Input v-model="add_info.contents" type="textarea" width="450" :autosize="{minRows: 3,maxRows: 8}" placeholder="#姓名#,本月是您入会周年庆,3倍积分等你来哦"></Input>
        </FormItem>
        <FormItem label="通道" prop="communicationVendorId">
          <Select v-model="add_info.communicationVendorId" placeholder="请选择" clearable>
            <Option v-for="item in cVendorsList" :value="item.id" :key="item.vendorName">{{ item.vendorName }}</Option>
          </Select>
        </FormItem>
      </Form>

      <Alert type="warning">字符数：{{add_info.length}}</Alert>
      <div slot="footer">
       
        <Button size="large" type="primary" @click="closeedit" :loading="loading">取消</Button>
        <Button size="large" type="primary" @click="editInfo('add_info')" :loading="loading">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  fetchList,
  deleteById,
  fetchVendorList,
  saveSmsTemplate,
  editSmsTemplate,
  testSms,
  enableTemplates
} from "@/api/sms";
export default {
  name: "list",
  components: {},
  data() {
    return {
      pageId:"targetPage", //跳转
      currIndex: 0, // 当前编辑和新增的行号
      searchState: false,
      showHeader: true, // 是否显示表头 @:show-header
      TableLoading: false, // 分页loading
      fixedHeader: false, // 是否固定表头 @:height
      tableSize: "small", // @:size
      DateReady: false, // 判断异步数据加载完成，避免报错
      loading: false, // save
      currIndex: 0,
      saveDisabled: false,

      current: 1,
      totalSize: 0, //总条数
      start: 1, //开始条数
      limit: 10, //每页记录数

      formItem: {
        name: ""
      },

      add_ruleValidate: {
        name: [
          {
            required: true,
            message: "请填写 模板名称",
            trigger: "blur"
          },
          {
            type: "string",
            max: 12,
            message: "模板名称长度不能大于12位",
            trigger: "blur"
          }
        ],
        contents: [
          {
            required: true,
            message: "请填写模板内容",
            trigger: "blur"
          },
          {
            type: "string",
            max: 64,
            message: "模板内容长度不能大于64位",
            trigger: "blur"
          }
        ],
        communicationVendorId: [
          {
            required: true,
            message: "请选择通道"
            //trigger: 'change'
          }
        ]
      },
      cVendorsList: [],
      add_info: {}, // 当前编辑和新增的行数据
      addModal: false,
      edit_info: {},
      editModal: false,
      editloading: false,

      testModal: false,
      test_info: {
        phone: ""
      },

      listStyle: {
        width: "280px",
        height: "300px"
      },

      listData: [], // @:data 列表数据
      columns1: [
        //列表表头
        {
          title: "模板ID",
          key: "id",
          align: "center",
          fixed: "left"
        },
        {
          title: "模板名称",
          key: "name",
          align: "center"
        },
        {
          title: "短信内容（每条短信62字符）",
          key: "contents",
          align: "center",
          tooltip: "true"
        },

        {
          title: "通道",
          key: "vendorName",
          align: "center"
        },

        {
          title: "字符数",
          key: "length",
          align: "center"
        },

        {
          title: "状态",
          key: "role",
          render: (h, params) => {
            const row = params.row;
            const color = row.status === 1 ? "success" : "error";
            const text = row.status === 1 ? "启用" : "停用";
            return h(
              "Tag",
              {
                props: {
                  type: "dot",
                  color: color
                }
              },
              text
            );
          }
        },

        {
          title: "操作",
          key: "actor",
          align: "center",
          fixed: "right",
          width:250,
          render: (h, params) => {
            if (this.listData[params.index].status === 0) {
              return h("div", [
                h(
                  "Button",
                  {
                    props: {
                      type: "info",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.testOpen(params.index);
                      }
                    }
                  },
                  "短信测试"
                ),

                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.editOpen(params.index);
                      }
                    }
                  },
                  "编辑"
                ),

                h(
                  "Button",
                  {
                    props: {
                      type: "error",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.remove(params);
                      }
                    }
                  },
                  "删除"
                ),

                h(
                  "Button",
                  {
                    props: {
                      type: "success",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.change(params);
                      }
                    }
                  },
                  "启用"
                )
              ]);
            } else {
              return h("div", [
                h(
                  "Button",
                  {
                    props: {
                      type: "error",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.change(params);
                      }
                    }
                  },
                  "停用"
                )
              ]);
            }
          }
        }
      ]
    };
  },
  watch: {
    params: {
      handler(val) {
        this.updateTableList(val);
      },
      deep: true
    },
    fixedHeader: {
      handler(val) {
        if (val) {
          this.$Message.info("表头已固定");
        }
      }
    },
    "add_info.contents": {
      handler(val) {
        this.add_info.length = this.add_info.contents.length;
      }
    }
  },
  computed: {
    state() {
      return this.$store.state.app;
    }
  },
  methods: {
    //筛选
    searchShow() {
      this.searchState = !this.searchState;
    },
    //	刷新页面
    refresh() {
      this.updateTableList();
    },
    //搜索
    queryTableList() {
      this.start = 1;
      this.updateTableList();
    },

    //分页
    changePageSize(pageSize) {
      this.limit = pageSize;
      this.updateTableList();
    },
    changeCurrent(current) {
      this.start = current;
      this.updateTableList();
    },

    goElevatorPage(pageId){  // 跳转按钮
      var evtObj;
      var thisPage=document.getElementById(pageId);
      var elevatorDiv=thisPage.getElementsByClassName("ivu-page-options-elevator");
      if(elevatorDiv && elevatorDiv.length>0){
        var pageInput = elevatorDiv[0].getElementsByTagName("input")[0];
        if (window.KeyEvent) {//firefox 浏览器下模拟事件
          evtObj = document.createEvent('KeyEvents');
          evtObj.initKeyEvent("keyup", true, true, window, true, false, false, false, 13, 0);
        } else {//chrome 浏览器下模拟事件
          evtObj = document.createEvent('UIEvents');
          evtObj.initUIEvent("keyup", true, true, window, 1);
          delete evtObj.keyCode;
          if (typeof evtObj.keyCode === "undefined") {//为了模拟keycode
            Object.defineProperty(evtObj, "keyCode", { value: 13 });
          } else {
            evtObj.key = String.fromCharCode(13);
          }
        }
        pageInput.dispatchEvent(evtObj);
      }
    },

    //列表
    updateTableList() {
      this.TableLoading = true;
      this.load = true;
      var reqParams = {
        name: this.formItem.name,
        // communication_channel_type_id: "3",
        page: this.start,
        limit: this.limit
      };
      fetchList(reqParams)
        .then(res => {
          this.TableLoading = true;
          this.load = true;
          if (res.data.code == 200) {
            this.totalSize = res.data.data.total;
            this.start = res.data.data.current;
            this.limit = res.data.data.size;
            this.listData = res.data.data.records;
            this.DateReady = true;
            this.TableLoading = false;
          }
        })
        .catch(error => {
          this.$Message.error("操作失败【" + error + "】");
        });
    },

    onSelect(selection, row) {},

    onSelectionChange(selection) {
      this.params.limit = selection;
    },

    //删除
    remove(params) {
      var self = this;
      this.$Modal.confirm({
        title: "删除确认",
        content: `是否确认删除此条记录`,
        onOk: function() {
          //this.$Loading.start();

          var reqParams = {
            id: params.row.id
          };

          deleteById(reqParams).then(res => {
            this.loading = false;

            if (res.data.data) {
              this.$Message.info("删除成功！");
              self.updateTableList();
            } else {
              this.$Message.error("删除失败!请稍后再试...!");
            }
          });
        }
      });
    },
    //更改状态
    change(params) {
      var self = this;
      this.$Modal.confirm({
        title: "更改状态",
        content: `是否确认更改状态`,
        onOk: function() {
          var statu;
          if (params.row.status == 0) {
            statu = 1; //停用改启用
          } else {
            statu = 0; //启用改停用
          }
          var reqParams = {
            id: params.row.id,
            status: statu
          };

          enableTemplates(reqParams).then(res => {
            if (res.data.data) {
              this.$Message.info("更改状态成功！");
              self.updateTableList();
            } else {
              this.$Message.error("更改状态失败!请稍后再试...!");
            }
          });
        }
      });
    },

    //打开测试短信
    testOpen(index) {
      this.test_info = this.listData[index];
      this.testModal = true;
      this.loading = false;
    },

    testInfo() {
      if (this.test_info.phone == "" || this.test_info.phone == undefined) {
        this.$Message.error("短信测试的手机号不能为空!");
        return;
      }
      var reqParams = {
        phone: this.test_info.phone,
        cTemplateId: this.test_info.id,
        resourceId: "123"
      };

      testSms(reqParams).then(res => {
        if (res.data.code == 200) {
          this.$Message.success("测试短信发送成功!");
          this.testModal = false;
          this.loading = false;
        } else {
          this.$Message.error(res.data.msg + "测试短信发送失败!请稍后再试...");

          this.loading = false;
        }
      });
    },
    getCVendorAll() {
      var reqParams = {
        type: 3
      };
      //通道
      fetchVendorList(reqParams).then(res => {
        if (res.data.code == 200) {
          this.cVendorsList = res.data.data;
        } else {
          this.$Message.error(res.data.msg);

          this.loading = false;
        }
      });
    },

    addOpen(index) {
      this.add_info = {};
      this.addModal = true;
      this.currIndex = index;
    },

    addInfo(name) {
      this.loading = true;
      this.$refs[name].validate(valid => {
        if (valid) {
          var reqParams = {
            //ctId: this.add_info.ctId,
            name: this.add_info.name, //名称
            //subject: this.add_info.subject, //主题
            contents: this.add_info.contents, //内容
            communicationChannelTypeId: "3", //沟通渠道类型 1-EDM 2-SMS 3-MMS 4-DM 5-Wechat 6-Call Center 7-Website
            communicationVendorId: this.add_info.communicationVendorId,
            length: this.add_info.length
            //communicationTemplateFields: cTFList,
          };

          saveSmsTemplate(reqParams).then(res => {
            if (res.data.code == 200) {
              this.$Message.success("添加成功!");
              this.updateTableList();
              this.addModal = false;
              this.loading = false;
            } else {
              this.$Message.error(res.data.msg);

              this.loading = false;
            }
          });
        } else {
          this.$Message.error("表单验证失败!");
          this.loading = false;
        }
      });
      this.splitphone();
    },
    editInfo(name) {
      this.editloading = true;
      this.$refs[name].validate(valid => {
        if (valid) {
          var reqParams = {
            id: this.add_info.id,
            name: this.add_info.name, //名称
            //subject: this.add_info.subject, //主题
            contents: this.add_info.contents, //内容
            communicationChannelTypeId: "3", //沟通渠道类型 1-EDM 2-SMS 3-MMS 4-DM 5-Wechat 6-Call Center 7-Website
            communicationVendorId: this.add_info.communicationVendorId,
            length: this.add_info.length
            //communicationTemplateFields: cTFList,
          };

          editSmsTemplate(reqParams).then(res => {
            if (res.data.code == 0) {
              this.$Message.success("修改成功!");
              this.updateTableList();
              this.editModal = false;
              this.loading = false;
            } else {
              this.$Message.error(res.data.msg);
              this.editloading = false;
            }
          });
        } else {
          this.$Message.error("表单验证失败!");
          this.loading = false;
        }
      });
    },

    editOpen(index) {
      this.add_info = this.listData[index];
      this.editModal = true;
      this.loading = false;
    },
    closeedit(index) {
      window.location.reload();
      this.editModal = false;
      this.loading = false;
    },

    splitphone() {
      // 拼接短信测试手机号
      this.phone = [...this.phone]
        .map((o, i) => (i % 11 == 10 ? o + ";" : o))
        .join("");
    }
  },
  created() {
    this.updateTableList();
    this.getCVendorAll();
  }
};
</script>

<style lang="less" scoped>
.search-filter {
  opacity: 0;
  display: none;
  overflow: hidden;
  transition: all 0.28s ease-out;
  &.active {
    opacity: 1;
    display: block;
  }
}
</style>
